<template>
  <div class="waybill-create" v-loading="pageLoading">
    <el-form class="waybill-create-form" :model="formModel">
      <div class="waybill-create-form-group">
        <p class="waybill-create-form-group__title">发货信息</p>
        <el-form-item class="waybill-create-form-chunk">
          <p class="waybill-create-form-chunk__title">
            发货人信息
            <el-button @click="showSelectSender = true">从客户中选择</el-button>
          </p>
          <div class="waybill-create-form-chunk__fields">
            <el-form-item label="发货人名称" label-position="top" prop="sendName">
              <el-input v-model="formModel.sendName"></el-input>
            </el-form-item>
            <el-form-item label="发货人手机" label-position="top" prop="sendPhone">
              <el-input v-model="formModel.sendPhone"></el-input>
            </el-form-item>
          </div>
        </el-form-item>
        <el-form-item label="发货日期" label-position="top" prop="sendDate">
          <el-date-picker
            type="datetime"
            placeholder="请选择发货时间"
            v-model="formModel.sendDate"
          />
        </el-form-item>
        <el-form-item label="发货地址" label-position="top">
          <hs-address v-model="sendAddress"></hs-address>
        </el-form-item>
      </div>
      <div class="waybill-create-form-group">
        <p class="waybill-create-form-group__title">收货信息</p>
        <el-form-item class="waybill-create-form-chunk">
          <p class="waybill-create-form-chunk__title">
            收货人信息
            <el-button @click="showSelectReceiver = true">从客户中选择</el-button>
          </p>
          <div class="waybill-create-form-chunk__fields">
            <el-form-item label="收货人名称" label-position="top" prop="receiveName">
              <el-input v-model="formModel.receiveName"></el-input>
            </el-form-item>
            <el-form-item label="收货人手机" label-position="top" prop="receivePhone">
              <el-input v-model="formModel.receivePhone"></el-input>
            </el-form-item>
          </div>
        </el-form-item>
        <!-- <el-form-item label="收货日期" label-position="top" prop="receiveDate">
          <el-date-picker
            type="datetime"
            placeholder="请选择发货时间"
            v-model="formModel.receiveDate"
          />
        </el-form-item> -->
        <el-form-item label="收货地址" label-position="top" prop="">
          <hs-address v-model="receiveAddress" />
        </el-form-item>
      </div>
      <div class="waybill-create-form-group">
        <p class="waybill-create-form-group__title">运单信息</p>
        <el-form-item label="运单状态" label-position="top">
          <el-select
            v-model="formModel.waybillStatus"
            placeholder="请选择运单状态"
            @change="statusChange"
          >
            <el-option
              :label="item.label"
              :value="item.value"
              v-for="item in waybillStatus"
              :key="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </div>
      <el-form-item
        label="网点信息"
        v-show="formModel.waybillStatus === 'received'"
        label-position="top"
      >
        <el-select v-model="formModel.branchId" placeholder="请选择网点">
          <el-option
            v-for="item in branchList"
            :key="item.branchId"
            :label="item.branchName"
            :value="item.branchId"
            :loading="branchLoading"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="运输车辆"
        label-position="top"
        v-show="formModel.waybillStatus === 'incar'"
        prop="carbillId"
      >
        <el-button @click="boundCarbill" v-if="!formModel.carbillId">+ 绑定出车单</el-button>
        <div class="waybill-create-form-chunk" v-else>
          <p class="waybill-create-form-chunk__title">
            发车信息
            <el-button @click="boundCarbill">从出车单中选择</el-button>
          </p>
          <div class="waybill-create-form-chunk__fields">
            <el-form-item label="车牌号" label-position="top">
              <el-input v-model="carbillDetail.driverLicense" readonly></el-input>
            </el-form-item>
            <el-form-item label="发车时间" label-position="top">
              <el-input v-model="carbillDetail.departDate" readonly></el-input>
            </el-form-item>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <div class="waybill-create-footer">
      <el-button>重置</el-button>
      <el-button type="primary">保存</el-button>
    </div>
  </div>
  <hs-select-user v-model:modelShow="showSelectSender" v-model="senderInfo" />
  <hs-select-user v-model:modelShow="showSelectReceiver" v-model="receiverInfo" />
</template>

<script setup>
import { computed, reactive, ref } from 'vue'
import HsSelectUser from '@/views/components/SelectUser'
import { Waybill_Status_Enum } from '@/common/enum'
import HsAddress from '@/views/components/Address'
import api from '@/http/index'
import _ from 'lodash'
import { useRoute, useRouter } from 'vue-router'
import { dayjs } from 'element-plus'
import customParseFormat from 'dayjs/plugin/customParseFormat'
const router = useRouter()
const localCacheKey = 'create.waybill.cache'
const waybillStatus = Object.keys(Waybill_Status_Enum).map((key) => ({
  label: Waybill_Status_Enum[key]?.text,
  value: key,
}))

const pageLoading = ref(false)
const showSelectSender = ref(false)
const showSelectReceiver = ref(false)

let formModel = reactive({
  senderId: '',
  sendName: '',
  sendPhone: '',
  sendDate: '',
  sendAddress: '',
  sendLng: '',
  sendLat: '',
  receiverId: '',
  receiveName: '',
  receivePhone: '',
  receiveDate: '',
  receiveAddress: '',
  receiveLng: '',
  receiveLat: '',
  waybillStatus: 'unreceive',
  branchId: '', // 网点Id
  carbillId: '',
})

const senderInfo = computed({
  get() {
    return {
      senderId: formModel.senderId,
      sendName: formModel.sendName,
      sendPhone: formModel.sendPhone,
    }
  },
  set(v) {
    formModel.senderId = v.userId
    formModel.sendName = v.nickName
    formModel.sendPhone = v.phonenumber
  },
})

const receiverInfo = computed({
  get() {
    return {
      receiverId: formModel.receiverId,
      receiveName: formModel.receiveName,
      receivePhone: formModel.receivePhone,
    }
  },
  set(v) {
    formModel.receiverId = v.userId
    formModel.receiveName = v.nickName
    formModel.receivePhone = v.phonenumber
  },
})

const sendAddress = computed({
  get() {
    return {
      address: formModel.sendAddress,
      lng: formModel.sendLng,
      lat: formModel.sendLat,
    }
  },
  set(v) {
    formModel.sendAddress = v.address
    formModel.sendLng = v.lng
    formModel.sendLat = v.lat
  },
})

const receiveAddress = computed({
  get() {
    return {
      address: formModel.receiveAddress,
      lng: formModel.receiveLng,
      lat: formModel.receiveLat,
    }
  },
  set(v) {
    formModel.receiveAddress = v.address
    formModel.receiveLng = v.lng
    formModel.receiveLat = v.lat
  },
})

const carbillDetail = ref({})
const getCarbillDetail = async () => {
  if (!formModel.carbillId) return
  api.carbill
    .detail({
      carbillId: formModel.carbillId,
    })
    .then((result) => {
      carbillDetail.value = {
        ...result.data,
        ...(result.data?.driver || {}),
        departDate: dayjs(result.data.departDate).format('YYYY/MM/DD h:m:s'),
      }
    })
}

const init = () => {
  pageLoading.value = true
  const cacheData = JSON.parse(localStorage.getItem(localCacheKey))
  if (cacheData) {
    formModel = cacheData
    localStorage.removeItem(localCacheKey)
  }
  if (formModel.carbillId && formModel.carbillId !== carbillDetail?.carbillId) {
    getCarbillDetail()
  }
  pageLoading.value = false
}
init()

const statusChange = () => {
  if (formModel.waybillStatus === 'received') {
    getBranchList()
  }
}

const branchLoading = ref(false)
const branchList = ref([])
const getBranchList = async () => {
  if (!_.isEmpty(branchList.value)) return
  branchLoading.value = true
  api.branch
    .list()
    .then((result) => {
      branchList.value = result.data
    })
    .finally(() => {
      branchLoading.value = false
    })
}

const boundCarbill = () => {
  localStorage.setItem(
    localCacheKey,
    JSON.stringify({
      ...formModel,
    }),
  )
  router.push({
    name: 'enterprise.carbill',
    query: {
      isSelect: 1,
      returnUrl: encodeURIComponent(location.href),
      localCacheKey,
    },
  })
}
</script>

<style lang="scss">
.waybill-create {
  height: 100%;
  overflow: auto;
  position: relative;
  &-form {
    padding: 20px;
    &__title {
      font-size: 16px;
      font-weight: 500;
      color: #262626;
      margin-bottom: 18px;
    }
    &-group {
      &__title {
        font-size: 16px;
        font-weight: 500;
        color: #262626;
        margin-bottom: 18px;
      }
    }
    &-chunk {
      width: 100%;
      background: #fafafa;
      padding: 18px 12px;
      margin-bottom: 18px;
      display: block;
      .el-form-item__content {
        display: block;
      }
      &__title {
        display: flex;
        align-items: center;
        line-height: 1;
        margin-bottom: 12px;
        color: #262626;
        > button {
          border: none;
          background-color: transparent;
          color: #409eff;
          padding: 4px;
          font-size: 12px;
          margin-left: 8px;
          height: fit-content;
        }
      }
      &__fields {
        display: flex;
        > * {
          flex: 1;
          margin-right: 24px;
        }
      }
    }
  }
  &-footer {
    width: 100%;
    position: sticky;
    bottom: 0;
    left: 0;
    height: 52px;
    padding: 10px;
    box-shadow: 6px 6px 12px 6px rgba(0, 0, 0, 0.08);
    background: #fff;
    z-index: 999;
    text-align: right;
  }
}
</style>
